package com.example.music.controller;

import com.example.commonutils.R;
import com.example.music.service.MsmService;
import com.example.music.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName MsmController
 * @Author: wx
 * @Create: 2022-10-29  19:56
 * @Description TODO
 * @Version: 1.0
 **/
@RestController
@RequestMapping("/msm")
@CrossOrigin
@Api(description="发送短信服务")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> template;

    @ApiOperation(value = "发送验证码")
    @GetMapping("/sendCode/{account}")
    public R sendCode(@PathVariable String account) {

        String code = template.opsForValue().get(account);
        if (!StringUtils.isEmpty(code)) {
            return R.success("成功");
        }
        //生成随机的验证码
        code = RandomUtil.getSixBitRandom();

        boolean isSend = msmService.sendMail(code, account);
        if (isSend) {
            System.out.println("生成的验证码：" + code);
            //发送成功，把发送成功的验证码放到redis，并设置有效时间
            template.opsForValue().set(account, code, 2, TimeUnit.MINUTES);
            return R.success("成功");
        } else {
            return R.error("短信发送失败");
        }
    }

}